//
//  JSModelEditViewController.m
//  JigSaw
//
//  Created by slim on 15/1/27.
//  Copyright (c) 2015年 LITB. All rights reserved.
//

#import "JSModelEditViewController.h"
#import "JSPreviewManager.h"
#import "UIColor+Help.h"
#import "UIImage+Help.h"
#import "UIImage+Resize.h"
#import "VSUtils.h"
#import "JSPatternEditView.h"
#import "JSModelEditView.h"
#import "NSDictionary+Json.h"
#import "AMBlurView.h"
#import "JSImageEditPopupView.h"
#import "JSDeviceInfo.h"
#import "JSModelManager.h"
#import "JSModelChooseCell.h"
#import "JSShareViewController.h"
#import "JSEditTextView.h"
#import "JSStencilItem.h"
#import "JSKeyboardView.h"
#import "JSTextLabel.h"
#import "UIView+border.h"
#import "JSFontManager.h"
#import "VSImageUtil.h"
//static NSString* jsonStr = @"{\"bestNum\":4,\"defaultBgColor\":\"#FFFFFFFF\",\"defaultPattern\":0,\"id\":\"qingxin\",\"imgMaxNum\":4,\"name\":\"qingxin\",\"outputHeight\":900,\"outputWidth\":600,\"stencilItems\":{\"1\":[{\"defaultText\":\"The Afternoon Times\",\"defaultTextColor\":\"#FF000000\",\"defaultTextSize\":30,\"defaultFont\":\"baskerville.ttf\",\"gravity\":17,\"height\":40,\"type\":2,\"width\":560,\"x\":20,\"y\":695,\"zorder\":0},{\"height\":560,\"type\":1,\"width\":560,\"x\":20,\"y\":25,\"zorder\":0,\"imgIndex\":0}],\"2\":[{\"defaultText\":\"The Afternoon Times\",\"defaultTextColor\":\"#FF000000\",\"defaultTextSize\":30,\"defaultFont\":\"baskerville.ttf\",\"gravity\":17,\"height\":40,\"type\":2,\"width\":560,\"x\":20,\"y\":695,\"zorder\":0},{\"height\":400,\"type\":1,\"width\":270,\"x\":28,\"y\":195,\"zorder\":0,\"imgIndex\":0},{\"height\":400,\"type\":1,\"width\":270,\"x\":302,\"y\":195,\"zorder\":0,\"imgIndex\":1}],\"3\":[{\"defaultText\":\"The Afternoon Times\",\"defaultTextColor\":\"#FF000000\",\"defaultTextSize\":30,\"defaultFont\":\"baskerville.ttf\",\"gravity\":17,\"height\":40,\"type\":2,\"width\":560,\"x\":20,\"y\":695,\"zorder\":0},{\"height\":300,\"type\":1,\"width\":484,\"x\":58,\"y\":80,\"zorder\":0,\"imgIndex\":0},{\"height\":210,\"type\":1,\"width\":240,\"x\":58,\"y\":384,\"zorder\":0,\"imgIndex\":1},{\"height\":210,\"type\":1,\"width\":240,\"x\":302,\"y\":384,\"zorder\":0,\"imgIndex\":2}],\"4\":[{\"defaultText\":\"The Afternoon Times\",\"defaultTextColor\":\"#FF000000\",\"defaultTextSize\":30,\"defaultFont\":\"baskerville.ttf\",\"gravity\":17,\"height\":40,\"type\":2,\"width\":560,\"x\":20,\"y\":735,\"zorder\":0},{\"height\":300,\"type\":1,\"width\":240,\"x\":58,\"y\":85,\"zorder\":0,\"imgIndex\":0},{\"height\":300,\"type\":1,\"width\":240,\"x\":302,\"y\":85,\"zorder\":0,\"imgIndex\":1},{\"height\":300,\"type\":1,\"width\":240,\"x\":58,\"y\":389,\"zorder\":0,\"imgIndex\":2},{\"height\":300,\"type\":1,\"width\":240,\"x\":302,\"y\":389,\"zorder\":0,\"imgIndex\":3}]},\"version\":100}";

@interface JSModelEditViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, JSTextLabelDelegate>

@property(nonatomic, weak)IBOutlet UIScrollView*         contentView;
@property(nonatomic, weak)IBOutlet AMBlurView*           editView;
@property(nonatomic, weak)IBOutlet AMBlurView*           bgBlurView;

@property(nonatomic, weak)IBOutlet UIView*               bgView;
@property(nonatomic, weak)IBOutlet UIView*               bgColorView;
@property(nonatomic, weak)IBOutlet UIView*               bgPatternView;
@property(nonatomic, assign)BOOL                         isEditViewHidden;
@property(nonatomic, assign)float                        adaptScale;
@property(nonatomic, assign)float                        outputScale;
@property(nonatomic, weak)IBOutlet UIButton*             editArrowBtn;
@property(nonatomic, weak)IBOutlet UIButton*             patternEditBtn;
@property(nonatomic, weak)IBOutlet UIButton*             modelChooseBtn;
@property(nonatomic, weak)IBOutlet UIView*               lineView0;
@property(nonatomic, weak)IBOutlet UIView*               lineView1;
@property(nonatomic, weak)IBOutlet JSPatternEditView*    patternContentView;
@property(nonatomic, weak)IBOutlet UICollectionView*     collectionView;
@property(nonatomic, strong)JSImageEditPopupView*        popupView;
@property(nonatomic, weak)JSModelEditView*               selectedView;
@property(nonatomic, strong)NSArray*                     stencilArray;
@property(nonatomic, strong)UIControl*                   transparentView;
@property(nonatomic, strong)JSTextLabel*                 editingTextLabel;
@property(nonatomic, strong)JSKeyboardView *             keyboardView;
@property(nonatomic, assign)CGFloat                      originalY;
@property(nonatomic, strong)NSIndexPath*                 selectedIndexPath;
@property(nonatomic ,weak)IBOutlet UIImageView*          blurImageView;

@property(nonatomic ,weak)IBOutlet UIImageView*          modelArrow;
@property(nonatomic ,weak)IBOutlet UIImageView*          patternArrow;
@property(nonatomic, copy)NSString* modelBundlePath;

@property(nonatomic, assign)BOOL isModelChoose;
@end
#define JS_EDITVIEW_SHOW_HEIGHT 205
#define JS_EDITVIEW_HIDE_HEIGHT 30
#define JS_APP_STATUS_BAR_HEIGHT 0

//#define BASE_CELL_WIDTH 60
//#define BASE_CELL_HEIGHT 90
//#define BASE_CELL_MIN_SPACE 9
//#define BASE_LINE_MIN_SPACE 10

@implementation JSModelEditViewController


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
   return [[JSModelManager sharedInstance] getProperModelByImageCount:self.imageAssets.count].count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   JSModelChooseCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"jsModelCell" forIndexPath:indexPath];
   JSStencilItemDesc* desc = [[JSModelManager sharedInstance] getProperModelByImageCount:self.imageAssets.count][indexPath.row];
   UIImage* image = [UIImage imageWithContentsOfFile:[self.modelBundlePath stringByAppendingPathComponent:desc.thumbnailPath]];
   cell.imageView.image = image;
   if ([JSModelManager sharedInstance].selectedModelIndex == desc.index) {
      self.selectedIndexPath = indexPath;
      [cell addBorder];
   }
   return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
   JSModelChooseCell* selectedCell = (JSModelChooseCell*)[collectionView cellForItemAtIndexPath:self.selectedIndexPath];
   [selectedCell removeBorder];
   JSModelChooseCell* cell = (JSModelChooseCell*)[collectionView cellForItemAtIndexPath:indexPath];
   [cell addBorder];
   self.selectedIndexPath = indexPath;
   JSStencilItemDesc* selectedDesc = [[JSModelManager sharedInstance] getProperModelByImageCount:self.imageAssets.count][indexPath.row];
   if ([JSModelManager sharedInstance].selectedModelIndex == selectedDesc.index) {
      return;
   }
   [JSModelManager sharedInstance].selectedModelIndex = selectedDesc.index;
   [self resetAllUIWhenSwitchModel];
   [self initMainUI];
}

- (void)resetAllUIWhenSwitchModel
{
   for(UIView *view in [self.bgPatternView subviews])
   {
      [view removeFromSuperview];
   }
   self.bgPatternView.backgroundColor = [UIColor clearColor];
   self.bgColorView.backgroundColor = [UIColor clearColor];
   [self.patternContentView resetColorButtons];
}


- (CGSize)calcContentSize
{
    CGSize retSize = CGSizeZero;
    //CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 2*D_ToolbarWidth-iOS7AddStatusHeight);
    CGFloat size_width = self.view.frame.size.width;
    CGFloat size_height = size_width * 4 /3.0f;
    if (size_height >= (self.view.frame.size.height-34)) {
        size_height = self.view.frame.size.height- 34;
        size_width = size_height * 3/4.0f;
    }
    retSize.width = size_width;
    retSize.height = size_height;
    return  retSize;
    
}

- (NSTextAlignment)getAlignmentFromGravity:(int)gravity
{
   if (17 == gravity) {
      return NSTextAlignmentCenter;
   } else if (51 == gravity) {
      //TODO模板数据有误
      return NSTextAlignmentLeft;
   } else if (19 == gravity) {
      return NSTextAlignmentLeft;
   }
   return NSTextAlignmentLeft;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
   if ([segue.identifier isEqualToString:@"showShare"]) {
      JSShareViewController* controller = segue.destinationViewController;
      controller.image = sender[0];
      controller.bgImage = sender[1];
   }
}

- (void)onBackButtonPressed:(id)sender
{
   [self.blurImageView removeFromSuperview];
   [super onBackButtonPressed:sender];
}

- (void)onRightButtonPressed:(id)sender
{
   [[UIApplication sharedApplication].keyWindow endEditing:NO];
   UIImage* image = [UIImage imageWithView:self.bgView];//[UIImage imageNamed:@"test.jpg"];
   image = [image resizedImage:CGSizeMake(image.size.width * 4, image.size.height * 4) interpolationQuality:kCGInterpolationHigh];
   NSData* data = UIImagePNGRepresentation(image);
   UIImage* pngImage = [UIImage imageWithData:data];
   UIImage* wholeImage = [UIImage imageWithView:self.view];
   UIImageWriteToSavedPhotosAlbum(pngImage, self, NULL, nil);
   [self performSegueWithIdentifier:@"showShare" sender:@[image, wholeImage]];
//   [data writeToFile:@"//Users/cabrite/Desktop/test.png" atomically:YES];
//   image = [UIImage scaleImage:image toScale:(1/self.outputScale)];
//   [self performSegueWithIdentifier:@"presentXQLib" sender:image];
}

- (void)addTransparentViewBelow:(UIView*)view
{
   if (!self.transparentView) {
      self.transparentView = [[UIControl alloc] initWithFrame:self.bgPatternView.frame];
      self.transparentView.backgroundColor = [UIColor clearColor];
      @weakify(self)
      [[self.transparentView rac_signalForControlEvents:UIControlEventTouchDown] subscribeNext:^(id x) {
         @strongify(self)
         if (!self.popupView.hidden) {
            self.popupView.hidden = YES;
         } else {
            //TODO
            [[UIApplication sharedApplication].keyWindow endEditing:YES];
            [self.transparentView removeFromSuperview];
            [self.keyboardView dismiss];
            self.keyboardView = nil;
         }
         [self.transparentView removeFromSuperview];
      }];
   }
   [self.bgPatternView insertSubview:self.transparentView belowSubview:view];
}

- (void)viewDidLoad {
   [super viewDidLoad];
   [self addRightButton];
   self.collectionView.layer.masksToBounds = NO;
   self.editView.bgColor = [UIColor colorWithHex:0x000000 alpha:0.6];
   self.bgBlurView.bgColor = [UIColor colorWithHex:0x000000 alpha:0.2];
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleXQSelected:) name:@"JS_NOTIFICATION_XQ_SELECTED" object:nil];
   self.modelBundlePath = [JSModelManager sharedInstance].modelBundlePath;
   self.stencilArray = [JSModelManager sharedInstance].stencils;//@[@"{\"bestNum\":1,\"defaultBgColor\":\"#FFFFFFFF\",\"defaultPattern\":0,\"id\":\"journey\",\"imgMaxNum\":4,\"name\":\"journey\",\"outputHeight\":900,\"outputWidth\":600,\"stencilItems\":{\"1\":[{\"height\":153,\"imgFileName\":\"title1.png\",\"type\":3,\"width\":62,\"x\":512,\"y\":30,\"zorder\":-1},{\"defaultText\":\"生命本身就是一场旅行。\",\"defaultTextColor\":\"#FF898989\",\"defaultTextSize\":18,\"defaultFont\":\"STHeitiSC-Light\",\"gravity\":51,\"height\":240,\"type\":2,\"width\":28,\"x\":25,\"y\":30,\"zorder\":0},{\"defaultText\":\"一个过程，一次发现，\",\"defaultTextColor\":\"#FF898989\",\"defaultTextSize\":18,\"defaultFont\":\"STHeitiSC-Light\",\"gravity\":51,\"height\":240,\"type\":2,\"width\":28,\"x\":50,\"y\":30,\"zorder\":0},{\"height\":500,\"type\":1,\"width\":550,\"x\":25,\"y\":280,\"zorder\":0,\"imgIndex\":0}],\"2\":[{\"height\":153,\"imgFileName\":\"title1.png\",\"type\":3,\"width\":62,\"x\":512,\"y\":30,\"zorder\":-1},{\"defaultText\":\"一个过程，一次发现，生命本身就是一场旅行。\",\"defaultTextColor\":\"#FF898989\",\"defaultTextSize\":18,\"defaultFont\":\"STHeitiSC-Light\",\"gravity\":51,\"height\":82,\"type\":2,\"width\":380,\"x\":40,\"y\":30,\"zorder\":0},{\"height\":300,\"type\":1,\"width\":560,\"x\":40,\"y\":240,\"zorder\":0,\"imgIndex\":0},{\"height\":300,\"type\":1,\"width\":560,\"x\":40,\"y\":550,\"zorder\":0,\"imgIndex\":1}],\"3\":[{\"height\":153,\"imgFileName\":\"title1.png\",\"type\":3,\"width\":62,\"x\":512,\"y\":30,\"zorder\":-1},{\"defaultText\":\"一个过程，一次发现，生命本身就是一场旅行。\",\"defaultTextColor\":\"#FF898989\",\"defaultTextSize\":18,\"defaultFont\":\"STHeitiSC-Light\",\"gravity\":51,\"height\":82,\"type\":2,\"width\":380,\"x\":40,\"y\":30,\"zorder\":0},{\"height\":300,\"type\":1,\"width\":560,\"x\":40,\"y\":240,\"zorder\":0,\"imgIndex\":0},{\"height\":300,\"type\":1,\"width\":275,\"x\":40,\"y\":550,\"zorder\":0,\"imgIndex\":1},{\"height\":300,\"type\":1,\"width\":275,\"x\":325,\"y\":550,\"zorder\":0,\"imgIndex\":2}],\"4\":[{\"height\":153,\"imgFileName\":\"title1.png\",\"type\":3,\"width\":62,\"x\":512,\"y\":30,\"zorder\":-1},{\"defaultText\":\"一个过程，一次发现，生命本身就是一场旅行。\",\"defaultTextColor\":\"#FF898989\",\"defaultTextSize\":18,\"defaultFont\":\"STHeitiSC-Light\",\"gravity\":51,\"height\":82,\"type\":2,\"width\":380,\"x\":40,\"y\":30,\"zorder\":0},{\"height\":320,\"type\":1,\"width\":560,\"x\":40,\"y\":240,\"zorder\":0,\"imgIndex\":0},{\"height\":145,\"type\":1,\"width\":250,\"x\":40,\"y\":570,\"zorder\":0,\"imgIndex\":1},{\"height\":145,\"type\":1,\"width\":250,\"x\":40,\"y\":725,\"zorder\":0,\"imgIndex\":2},{\"height\":300,\"type\":1,\"width\":300,\"x\":300,\"y\":570,\"zorder\":0,\"imgIndex\":3}]},\"version\":100}", @"{\"bestNum”:2,”defaultBgColor\":\"#FFFFFFFF\",\"defaultPattern\":0,\"id\":\"youandme\",\"imgMaxNum\":4,\"name\":\"youandme\",\"outputHeight\":900,\"outputWidth\":600,\"stencilItems\":{\"1\":[{\"height\":128,\"imgFileName\":\"title2.png\",\"type\":3,\"width\":166,\"x\":25,\"y\":742,\"zorder\":-1},{\"defaultText\":\"somewhere only belongs to us,I want you to know my sweet emotion.\",\"defaultTextColor\":\"#FF898989\",\"defaultTextSize\":20,\"defaultFont\":\"Baskerville-Italic\",\"gravity\":51,\"height\":53,\"type\":2,\"width\":300,\"x\":300,\"y\":824,\"zorder\":0},{\"height\":660,\"type\":1,\"width\":600,\"x\":0,\"y\":0,\"zorder\":0,\"imgIndex\":0}],\"2\":[{\"height\":147,\"imgFileName\":\"title2.png\",\"type\":3,\"width\":190,\"x\":205,\"y\":377,\"zorder\":-1},{\"height\":350,\"type\":1,\"width\":600,\"x\":0,\"y\":0,\"zorder\":0,\"imgIndex\":0},{\"height\":350,\"type\":1,\"width\":600,\"x\":0,\"y\":550,\"zorder\":0,\"imgIndex\":1}],\"3\":[{\"height\":128,\"imgFileName\":\"title2.png\",\"type\":3,\"width\":166,\"x\":25,\"y\":742,\"zorder\":-1},{\"defaultText\":\"somewhere only belongs to us,I want you to know my sweet emotion.\",\"defaultTextColor\":\"#FF898989\",\"defaultTextSize\":20,\"defaultFont\":\"Baskerville-Italic\",\"gravity\":51,\"height\":53,\"type\":2,\"width\":300,\"x\":300,\"y\":824,\"zorder\":0},{\"height\":340,\"type\":1,\"width\":340,\"x\":5,\"y\":5,\"zorder\":0,\"imgIndex\":0},{\"height\":340,\"type\":1,\"width\":245,\"x\":350,\"y\":5,\"zorder\":0,\"imgIndex\":1},{\"height\":340,\"type\":1,\"width\":590,\"x\":5,\"y\":350,\"zorder\":0,\"imgIndex\":2}],\"4\":[{\"height\":128,\"imgFileName\":\"title2.png\",\"type\":3,\"width\":166,\"x\":25,\"y\":742,\"zorder\":-1},{\"defaultText\":\"somewhere only belongs to us,I want you to know my sweet emotion.\",\"defaultTextColor\":\"#FF898989\",\"defaultTextSize\":20,\"defaultFont\":\"Baskerville-Italic\",\"gravity\":51,\"height\":53,\"type\":2,\"width\":300,\"x\":300,\"y\":824,\"zorder\":0},{\"height\":340,\"type\":1,\"width\":340,\"x\":5,\"y\":5,\"zorder\":0,\"imgIndex\":0},{\"height\":340,\"type\":1,\"width\":245,\"x\":350,\"y\":5,\"zorder\":0,\"imgIndex\":1},{\"height\":340,\"type\":1,\"width\":245,\"x\":5,\"y\":350,\"zorder\":0,\"imgIndex\":2},{\"height\":340,\"type\":1,\"width\":340,\"x\":255,\"y\":350,\"zorder\":0,\"imgIndex\":3}]},\"version\":100}", @"{\"bestNum\":3,\"defaultBgColor\":\"#FFFFFFFF\",\"defaultPattern\":0,\"id\":\"food\",\"imgMaxNum\":4,\"name\":\"food\",\"outputHeight\":900,\"outputWidth\":600,\"stencilItems\":{\"1\":[{\"height\":146,\"imgFileName\":\"title3.png\",\"type\":3,\"width\":224,\"x\":25,\"y\":44,\"zorder\":-1},{\"height\":80,\"imgFileName\":\"slogan.png\",\"type\":3,\"width\":50,\"x\":527,\"y\":192,\"zorder\":-1},{\"defaultText\":\"sensuous food, emotional taste.\",\"defaultTextColor\":\"#FF000000\",\"defaultTextSize\":22,\"defaultFont\":\"SnellRoundhand\",\"gravity\":19,\"height\":38,\"type\":2,\"width\":500,\"x\":25,\"y\":242,\"zorder\":0},{\"height\":550,\"type\":1,\"width\":550,\"x\":25,\"y\":305,\"zorder\":0,\"imgIndex\":0}],\"2\":[{\"height\":146,\"imgFileName\":\"title3.png\",\"type\":3,\"width\":224,\"x\":25,\"y\":44,\"zorder\":-1},{\"height\":80,\"imgFileName\":\"slogan.png\",\"type\":3,\"width\":50,\"x\":500,\"y\":790,\"zorder\":-1},{\"defaultText\":\"sensuous food, emotional taste.\",\"defaultTextColor\":\"#FF000000\",\"defaultTextSize\":22,\"defaultFont\":\"SnellRoundhand\",\"gravity\":19,\"height\":38,\"type\":2,\"width\":550,\"x\":25,\"y\":242,\"zorder\":0},{\"height\":280,\"type\":1,\"width\":440,\"x\":25,\"y\":300,\"zorder\":0,\"imgIndex\":0},{\"height\":280,\"type\":1,\"width\":440,\"x\":25,\"y\":590,\"zorder\":0,\"imgIndex\":1}],\"3\":[{\"height\":146,\"imgFileName\":\"title3.png\",\"type\":3,\"width\":224,\"x\":25,\"y\":44,\"zorder\":-1},{\"height\":80,\"imgFileName\":\"slogan.png\",\"type\":3,\"width\":50,\"x\":504,\"y\":192,\"zorder\":-1},{\"defaultText\":\"sensuous food, emotional taste.\",\"defaultTextColor\":\"#FF000000\",\"defaultTextSize\":22,\"defaultFont\":\"SnellRoundhand\",\"gravity\":19,\"height\":38,\"type\":2,\"width\":480,\"x\":25,\"y\":242,\"zorder\":0},{\"height\":464,\"type\":1,\"width\":296,\"x\":0,\"y\":348,\"zorder\":0,\"imgIndex\":0},{\"height\":230,\"type\":1,\"width\":300,\"x\":300,\"y\":348,\"zorder\":0,\"imgIndex\":1},{\"height\":230,\"type\":1,\"width\":300,\"x\":300,\"y\":582,\"zorder\":0,\"imgIndex\":2}],\"4\":[{\"height\":146,\"imgFileName\":\"title3.png\",\"type\":3,\"width\":224,\"x\":25,\"y\":44,\"zorder\":-1},{\"height\":80,\"imgFileName\":\"slogan.png\",\"type\":3,\"width\":50,\"x\":504,\"y\":192,\"zorder\":-1},{\"defaultText\":\"sensuous food, emotional taste.\",\"defaultTextColor\":\"#FF000000\",\"defaultTextSize\":22,\"defaultFont\":\"SnellRoundhand\",\"gravity\":19,\"height\":38,\"type\":2,\"width\":480,\"x\":30,\"y\":242,\"zorder\":0},{\"height\":320,\"type\":1,\"width\":300,\"x\":30,\"y\":320,\"zorder\":0,\"imgIndex\":0},{\"height\":250,\"type\":1,\"width\":240,\"x\":360,\"y\":320,\"zorder\":0,\"imgIndex\":1},{\"height\":180,\"type\":1,\"width\":300,\"x\":30,\"y\":650,\"zorder\":0,\"imgIndex\":2},{\"height\":250,\"type\":1,\"width\":240,\"x\":360,\"y\":580,\"zorder\":0,\"imgIndex\":3}]},\"version\":100}", @"{\"bestNum\":4,\"defaultBgColor\":\"#FFFFFFFF\",\"defaultPattern\":0,\"id\":\"qingxin\",\"imgMaxNum\":4,\"name\":\"qingxin\",\"outputHeight\":900,\"outputWidth\":600,\"stencilItems\":{\"1\":[{\"defaultText\":\"The Afternoon Times\",\"defaultTextColor\":\"#FF000000\",\"defaultTextSize\":30,\"defaultFont\":\"Baskerville-Italic\",\"gravity\":17,\"height\":120,\"type\":2,\"width\":560,\"x\":20,\"y\":695,\"zorder\":0},{\"height\":560,\"type\":1,\"width\":560,\"x\":20,\"y\":25,\"zorder\":0,\"imgIndex\":0}],\"2\":[{\"defaultText\":\"The Afternoon Times\",\"defaultTextColor\":\"#FF000000\",\"defaultTextSize\":30,\"defaultFont\":\"Baskerville-Italic\",\"gravity\":17,\"height\":120,\"type\":2,\"width\":560,\"x\":20,\"y\":695,\"zorder\":0},{\"height\":400,\"type\":1,\"width\":270,\"x\":28,\"y\":195,\"zorder\":0,\"imgIndex\":0},{\"height\":400,\"type\":1,\"width\":270,\"x\":302,\"y\":195,\"zorder\":0,\"imgIndex\":1}],\"3\":[{\"defaultText\":\"The Afternoon Times\",\"defaultTextColor\":\"#FF000000\",\"defaultTextSize\":30,\"defaultFont\":\"Baskerville-Italic\",\"gravity\":17,\"height\":120,\"type\":2,\"width\":560,\"x\":20,\"y\":695,\"zorder\":0},{\"height\":300,\"type\":1,\"width\":484,\"x\":58,\"y\":80,\"zorder\":0,\"imgIndex\":0},{\"height\":210,\"type\":1,\"width\":240,\"x\":58,\"y\":384,\"zorder\":0,\"imgIndex\":1},{\"height\":210,\"type\":1,\"width\":240,\"x\":302,\"y\":384,\"zorder\":0,\"imgIndex\":2}],\"4\":[{\"defaultText\":\"The Afternoon Times\",\"defaultTextColor\":\"#FF000000\",\"defaultTextSize\":30,\"defaultFont\":\"Baskerville-Italic\",\"gravity\":17,\"height\":120,\"type\":2,\"width\":560,\"x\":20,\"y\":735,\"zorder\":0},{\"height\":300,\"type\":1,\"width\":240,\"x\":58,\"y\":85,\"zorder\":0,\"imgIndex\":0},{\"height\":300,\"type\":1,\"width\":240,\"x\":302,\"y\":85,\"zorder\":0,\"imgIndex\":1},{\"height\":300,\"type\":1,\"width\":240,\"x\":58,\"y\":389,\"zorder\":0,\"imgIndex\":2},{\"height\":300,\"type\":1,\"width\":240,\"x\":302,\"y\":389,\"zorder\":0,\"imgIndex\":3}]},\"version\":100}"];
   self.adaptScale = [JSDeviceInfo getScreenScale];
   CGFloat eidtWidth = [VSUtils screenWidth] - 30;
   CGFloat outputWidth = 300 * self.adaptScale;
   self.outputScale = eidtWidth/outputWidth;
   [self initMainUI];

   self.view.backgroundColor = [UIColor colorWithHex:0xe8e8e8];
   self.lineView0.backgroundColor = [UIColor colorWithHex:0xffffff alpha:0.1];
   self.lineView0.hidden = YES;
   self.lineView1.backgroundColor = [UIColor colorWithHex:0xffffff alpha:0.1];
   self.bgPatternView.backgroundColor = [UIColor clearColor];
   self.bgColorView.backgroundColor = [UIColor clearColor];
   self.modelChooseBtn.backgroundColor = [UIColor clearColor];
   self.patternContentView.backgroundColor = [UIColor clearColor];
   self.collectionView.backgroundColor = [UIColor clearColor];
   self.collectionView.hidden = YES;
   self.isEditViewHidden = NO;
   [self.editArrowBtn addTarget:self action:@selector(editArrowBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
   [self.patternEditBtn addTarget:self action:@selector(patternEditBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
   [self.modelChooseBtn addTarget:self action:@selector(modelChooseBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
   [self.patternEditBtn setTitleColor:[UIColor colorWithHex:0xffe049] forState:UIControlStateNormal];
   self.modelArrow.clipsToBounds = YES;
   self.patternArrow.clipsToBounds = YES;
   self.patternArrow.image = [UIImage imageNamed:@"btn_bg_click"];
   self.modelArrow.image = [UIImage imageNamed:@"btn_bg"];

   [self setColorBtn];
   [self setPatternBtn];
   self.title = NSLocalizedString(@"制作拼图", @"");
   self.popupView = [JSImageEditPopupView initCustomView];
   [self.view addSubview:self.popupView];
   self.popupView.hidden = YES;
   @weakify(self)
   self.popupView.rotateBlk = ^(){
      @strongify(self)
      [self rotateImageView:self.selectedView];
   };
   self.popupView.zoomInBlk = ^(){
      @strongify(self)
      [self.selectedView zoomIn];
   };
   self.popupView.zoomOutBlk = ^(){
      @strongify(self)
      [self.selectedView zoomOut];
   };
   self.popupView.switchBlk = ^(){
      @strongify(self)
      [self mirrorImageView:self.selectedView];
   };

}

- (void)viewWillDisappear:(BOOL)animated
{
   [super viewWillDisappear:animated];
   [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
   [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
   [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
   [super viewWillAppear:animated];
   [[JSPreviewManager sharedInstance] hiddenPreView];
   [self hideEditView];
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShowNotification:) name:UIKeyboardDidShowNotification object:nil];
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
   [super viewDidAppear:animated];
   //   添加模糊背景 begin
   id asset = [self.imageAssets objectAtIndex:0];
   UIImage* image = nil;
   if ([asset isKindOfClass:[ALAsset class]]) {
      image = [UIImage imageWithCGImage:((ALAsset*)asset).defaultRepresentation.fullScreenImage];
   } else if ([asset isKindOfClass:[PGJSImageItem class]]) {
      image = ((PGJSImageItem*)asset).orgImage;
   }
   self.blurImageView.image = image;
   //   添加模糊背景 end

   self.bgView.translatesAutoresizingMaskIntoConstraints = YES;
   self.bgView.layer.shadowOpacity = 0.1;
   self.bgView.layer.shadowColor = [[UIColor colorWithHex:0x000000] CGColor];
   self.bgView.layer.shadowOffset = CGSizeMake(0, 2);
   self.bgView.layer.masksToBounds = NO;
   self.bgView.layer.shadowPath = [[UIBezierPath bezierPathWithRect:self.bgView.bounds] CGPath];
   self.bgView.layer.shadowRadius = 1;
   self.originalY = self.bgView.frame.origin.y;
}

- (void)setPatternBtn
{
   @weakify(self)
   self.patternContentView.patternBtn0Blk = ^ {
      @strongify(self)
      self.bgPatternView.backgroundColor = nil;
   };
   self.patternContentView.patternBtn1Blk = ^ {
      @strongify(self)
      UIColor* color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pattern1"]];
      self.bgPatternView.backgroundColor = color;
   };
   self.patternContentView.patternBtn2Blk = ^ {
      @strongify(self)
      UIColor* color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pattern2"]];
      self.bgPatternView.backgroundColor = color;
   };
   self.patternContentView.patternBtn3Blk = ^ {
      @strongify(self)
      UIColor* color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pattern3"]];
      self.bgPatternView.backgroundColor = color;
   };
   self.patternContentView.patternBtn4Blk = ^ {
      @strongify(self)
      UIColor* color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pattern4"]];
      self.bgPatternView.backgroundColor = color;
   };
   self.patternContentView.patternBtn5Blk = ^ {
      @strongify(self)
      UIColor* color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pattern5"]];
      self.bgPatternView.backgroundColor = color;
   };

}

- (void)setColorBtn
{
   @weakify(self)
   self.patternContentView.colorBtn0Blk = ^(id o){
      @strongify(self)
      self.bgColorView.backgroundColor = (UIColor*)o;
   };
   self.patternContentView.colorBtn1Blk = ^(id o){
      @strongify(self)
      self.bgColorView.backgroundColor = (UIColor*)o;
   };
   self.patternContentView.colorBtn2Blk = ^(id o){
      @strongify(self)
      self.bgColorView.backgroundColor = (UIColor*)o;
   };
   self.patternContentView.colorBtn3Blk = ^(id o){
      @strongify(self)
      self.bgColorView.backgroundColor = (UIColor*)o;
   };
   self.patternContentView.colorBtn4Blk = ^(id o){
      @strongify(self)
      self.bgColorView.backgroundColor = (UIColor*)o;
   };
   self.patternContentView.colorBtn5Blk = ^(id o){
      @strongify(self)
      self.bgColorView.backgroundColor = (UIColor*)o;
   };
   self.patternContentView.colorBtn6Blk = ^(id o){
      @strongify(self)
      self.bgColorView.backgroundColor = (UIColor*)o;
   };
}
- (CGFloat)getProperValue:(float)value
{
   return value / 2 * self.adaptScale * self.outputScale;
}
- (void)initMainUI
{
   NSDictionary* stencilItems = [[JSModelManager sharedInstance] getCurrentStencilItems];
   NSUInteger imageCount = self.imageAssets.count;
   NSArray* stencilItemArray = [stencilItems objectForKey:[NSString stringWithFormat:@"%lu", (unsigned long)imageCount]];
   __block NSMutableArray * hitTestEditViews = [@[] mutableCopy];
   for (NSDictionary* dic in stencilItemArray) {
      JSStencilItem* item = [[JSModelManager sharedInstance] parseDictToStencilItem:dic];
      CGFloat x = [self getProperValue:[item.x floatValue]];
      CGFloat y = [self getProperValue:[item.y floatValue]];
      CGFloat width = [self getProperValue:[item.width floatValue]];
      CGFloat height = [self getProperValue:[item.height floatValue]];
      CGRect rect = CGRectMake(x, y, width, height);
//      int type = [[item objectForKey:@"type"] integerValue];
//      switch (type) {
//         case E_ITEM_IMAGE:
//            break;
//         case E_ITEM_TEXT:
//            break;
//         case E_ITEM_DECORATION:
//            break;
//         default:
//            break;
//      }
      if (item.type.integerValue == 1) {
         JSModelEditView* modelEditView = [[JSModelEditView alloc] initWithFrame:rect];
         [hitTestEditViews addObject:modelEditView];
         id asset = [self.imageAssets objectAtIndex:item.imgIndex.unsignedIntegerValue];
         UIImage* image = nil;
         if ([asset isKindOfClass:[ALAsset class]]) {
            image = [UIImage imageWithCGImage:((ALAsset*)asset).defaultRepresentation.fullScreenImage];
         } else if ([asset isKindOfClass:[PGJSImageItem class]]) {
            image = ((PGJSImageItem*)asset).orgImage;
         }
         UIImage* maskImage = nil;
         if (item.maskFileName.length > 0) {
            NSString* maskImagePath = [self.modelBundlePath stringByAppendingPathComponent:item.maskFileName];
            maskImage = [UIImage imageWithContentsOfFile:maskImagePath];
         }
         //先使用原图显示模板中图片
         [modelEditView setImageViewData:image withMaskImage:maskImage];
         //异步获取滤镜特效的图片，获取OK后设置到模板中
         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //TODO 阻塞接口，根据滤镜参数获取滤镜特效的图片
            //UIImage* filerImage = [PGXXX getFilterImage:image withParameters:withParameter];
            dispatch_async(dispatch_get_main_queue(), ^{
               //使用制作好特效的图片替换模板中的原图
               //[modelEditView setImageViewData:filerImage withMaskImage:maskImage];
            });
         });

         @weakify(self)
         modelEditView.tapBlk = ^(CGPoint point, id sender) {
            @strongify(self)
            CGPoint convertPoint = [self.view convertPoint:point fromView:self.bgPatternView];
            CGFloat x = convertPoint.x - 115 > 0 ? convertPoint.x - 115 : 0;
            if (x + 183 > self.bgPatternView.frame.size.width) {
               x = self.bgPatternView.frame.size.width - 183;
            }
            self.popupView.frame = CGRectMake(x, convertPoint.y - 41, self.popupView.frame.size.width, self.popupView.frame.size.height);
//            BOOL hidden = self.popupView.hidden;
            self.popupView.hidden = NO;
            self.selectedView = sender;
            [self addTransparentViewBelow:self.popupView];
         };
         modelEditView.longPressedBlk = ^(CGPoint point, id sender) {
            @strongify(self)
            [hitTestEditViews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
               JSModelEditView * editView = obj;
               if (sender != editView) {
                  if ([editView pointInside:[self.bgPatternView convertPoint:point toView:obj] withEvent:nil]) {
                     [editView contentShrink];
                  }
                  else
                  {
                     [editView contentExpand];
                  }
               }
            }];
         };
         modelEditView.longPressedReleasedBlk = ^(CGPoint point, id sender) {
            @strongify(self)
            [hitTestEditViews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
               JSModelEditView * editView = obj;
               if (sender != editView) {
                  if ([editView pointInside:[self.bgPatternView convertPoint:point toView:obj] withEvent:nil]) {
                     JSModelEditView * originEditView = sender;
                     UIImage * tempImage = editView.imageview.image;
                     UIImage * tempMaskImage = editView.maskImage;
                     [editView setImageViewData:originEditView.imageview.image withMaskImage:originEditView.maskImage];
                     [originEditView setImageViewData:tempImage withMaskImage:tempMaskImage];
                     [editView contentExpand];
                  }
               }
            }];
         };

//         modelEditView.layer.zPosition = item.zorder.floatValue;
         [self.bgPatternView addSubview:modelEditView];
      } else if ([item.type integerValue] == 2) {
         JSTextLabel* textLabel = [[JSTextLabel alloc] initWithFrame:rect];
         UIFont* font = [UIFont fontWithName:item.defaultFont size:item.defaultTextSize.floatValue / 2];
         if (!font) {
            UIFontDescriptor * fontDescriptor = [UIFontDescriptor fontDescriptorWithName:item.defaultFont size:item.defaultTextSize.floatValue / 2];
            font = [UIFont fontWithDescriptor:fontDescriptor size:item.defaultTextSize.floatValue / 2];
         }
         textLabel.defaultFontSize = item.defaultTextSize.floatValue / 2;
         textLabel.minimumFontSize = item.defaultTextSize.floatValue / 2 - 2;
         int gravity = item.gravity.intValue;
         NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
         paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
         paragraphStyle.alignment = [self getAlignmentFromGravity:gravity];
         NSDictionary *attributes = @{NSFontAttributeName : font, NSParagraphStyleAttributeName : paragraphStyle};
         textLabel.attributedText = [[NSAttributedString alloc] initWithString:item.defaultText attributes:attributes];
         textLabel.backgroundColor = [UIColor clearColor];
         UIColor* color = [UIColor colorWithHexString:item.defaultTextColor];
         textLabel.textColor = color;
//         textView.layer.zPosition = item.zorder.floatValue;
         [self.bgPatternView addSubview:textLabel];
         textLabel.delegate = self;
      } else if ([item.type integerValue] == 3) {
         UIImageView* iv = [[UIImageView alloc] initWithFrame:rect];
         NSString* imagePath = [self.modelBundlePath stringByAppendingPathComponent:item.imgFileName];
         iv.image = [UIImage imageWithContentsOfFile:imagePath];
//         iv.layer.zPosition = item.zorder.floatValue;
         [self.bgPatternView addSubview:iv];
      } else if ([item.type integerValue] == 4) {
         UIView* lineView = [[UIView alloc] initWithFrame:rect];
         lineView.backgroundColor = [UIColor colorWithHexString:item.backgroudColor];
         [self.bgPatternView addSubview:lineView];
      } else if ([item.type integerValue] == 5) {
         UILabel* dateLable = [[UILabel alloc] initWithFrame:rect];
         dateLable.textColor = [UIColor colorWithHexString:item.defaultTextColor];
         NSDate* date = [NSDate date];
         NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
         formatter.dateFormat = item.dateFormat;
         dateLable.text = [formatter stringFromDate:date];
         dateLable.textAlignment = [self getAlignmentFromGravity:item.gravity.intValue];
         UIFont* font = [UIFont fontWithName:item.defaultFont size:item.defaultTextSize.floatValue / 2];
         if (!font) {
            UIFontDescriptor * fontDescriptor = [UIFontDescriptor fontDescriptorWithName:item.defaultFont size:item.defaultTextSize.floatValue / 2];
            font = [UIFont fontWithDescriptor:fontDescriptor size:item.defaultTextSize.floatValue / 2];
         }
         dateLable.font = font;
         [self.bgPatternView addSubview:dateLable];
      }
   }
}

- (void)mirrorImageView:(JSModelEditView*)modelEditView
{
   UIImage* image = [modelEditView.imageview.image rotate:UIImageOrientationUpMirrored];
   [modelEditView setImageViewData:image withMaskImage:nil];
}
- (void)rotateImageView:(JSModelEditView*)modelEditView
{
   UIImage* image = [modelEditView.imageview.image rotate:UIImageOrientationRight];
   [modelEditView setImageViewData:image withMaskImage:nil];
}

- (void)modelChooseBtnClicked:(id)sender
{
   if (self.isModelChoose) {
      return;
   }
   CGFloat screenWidth = [VSUtils screenWidth];
   [self.modelChooseBtn setTitleColor:[UIColor colorWithHex:0xffe049] forState:UIControlStateNormal];
   [self.patternEditBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
   self.patternArrow.image = [UIImage imageNamed:@"btn_bg"];
   self.modelArrow.image = [UIImage imageNamed:@"btn_bg_click"];
   if (self.collectionView.frame.origin.x == 10) {
      //第一次进入模板选择时，collectionView先移动到右边
      CGRect rect = self.collectionView.frame;
      self.collectionView.frame = CGRectMake(rect.origin.x + screenWidth, rect.origin.y, rect.size.width, rect.size.height);
   }
   @weakify(self)
   [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
      @strongify(self)
      CGRect rect = self.patternContentView.frame;
      self.patternContentView.frame = CGRectMake(rect.origin.x - screenWidth, rect.origin.y, rect.size.width, rect.size.height);
      rect = self.collectionView.frame;
      self.collectionView.frame = CGRectMake(rect.origin.x - screenWidth, rect.origin.y, rect.size.width, rect.size.height);
      self.collectionView.hidden = NO;
   } completion:NULL];
   self.isModelChoose = YES;
}

- (void)patternEditBtnClicked:(id)sender
{
   if (!self.isModelChoose) {
      return;
   }
   CGFloat screenWidth = [VSUtils screenWidth];
   [self.patternEditBtn setTitleColor:[UIColor colorWithHex:0xffe049] forState:UIControlStateNormal];
   [self.modelChooseBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
   self.patternArrow.image = [UIImage imageNamed:@"btn_bg_click"];
   self.modelArrow.image = [UIImage imageNamed:@"btn_bg"];
   if (self.patternContentView.frame.origin.x == 0) {
      //第一次进入模板选择时，patternContentView先移动到右边
      CGRect rect = self.patternContentView.frame;
      self.patternContentView.frame = CGRectMake(rect.origin.x - screenWidth, rect.origin.y, rect.size.width, rect.size.height);
   }
   @weakify(self)
   [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
      @strongify(self)
      CGRect rect = self.collectionView.frame;
      self.collectionView.frame = CGRectMake(rect.origin.x + screenWidth, rect.origin.y, rect.size.width, rect.size.height);
      rect = self.patternContentView.frame;
      self.patternContentView.frame = CGRectMake(rect.origin.x + screenWidth, rect.origin.y, rect.size.width, rect.size.height);
      self.patternContentView.hidden = NO;
   } completion:NULL];
   self.isModelChoose = NO;
}

- (void)editArrowBtnClicked:(id)sender
{
   if (self.isModelChoose) {
      self.patternContentView.hidden = YES;
   } else {
      self.collectionView.hidden = YES;
   }
   [self setEditViewHiddenWithAnimate:!self.isEditViewHidden];
}

- (void)setEditViewHiddenWithAnimate:(BOOL)hidden
{
   if (hidden == self.isEditViewHidden) {
      return;
   }
   self.isEditViewHidden = hidden;
   CGFloat y = 0;
   CGFloat screenHeight = [VSUtils screenHeight];
   CGFloat screenWidth = [VSUtils screenWidth];
   if (hidden) {
      y = screenHeight - JS_APP_STATUS_BAR_HEIGHT - JS_EDITVIEW_HIDE_HEIGHT;
   } else {
      y = screenHeight - JS_APP_STATUS_BAR_HEIGHT - JS_EDITVIEW_SHOW_HEIGHT;
   }
   CGRect newRect = CGRectMake(0, y, screenWidth, JS_EDITVIEW_SHOW_HEIGHT);
   self.editView.translatesAutoresizingMaskIntoConstraints = YES;
   @weakify(self)
   [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
      @strongify(self)
      self.editView.frame = newRect;
   } completion:^(BOOL finished) {
      if (hidden) {
         [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            @strongify(self)
            CGAffineTransform at =CGAffineTransformMakeRotation(-2*M_PI);
            [self.editArrowBtn setTransform:at];
         } completion:NULL];
      } else {
         [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            @strongify(self)
            CGAffineTransform at =CGAffineTransformMakeRotation(M_PI);
            [self.editArrowBtn setTransform:at];
         } completion:NULL];
      }
   }];
}

- (void)hideEditView
{
   if (YES == self.isEditViewHidden) {
      return;
   }
   self.isEditViewHidden = YES;
   CGFloat screenHeight = [VSUtils screenHeight];
   CGFloat screenWidth = [VSUtils screenWidth];
   CGFloat y = screenHeight - JS_APP_STATUS_BAR_HEIGHT - JS_EDITVIEW_HIDE_HEIGHT;
   [self.editArrowBtn setImage:[UIImage imageNamed:@"up_arrow"] forState:UIControlStateNormal];
   [self.editArrowBtn setImage:[UIImage imageNamed:@"up_arrow_click"] forState:UIControlStateHighlighted];
   CGRect newRect = CGRectMake(0, y, screenWidth, JS_EDITVIEW_SHOW_HEIGHT);
   self.editView.translatesAutoresizingMaskIntoConstraints = YES;
   self.editView.frame = newRect;
}

- (void)handleKeyboardWillShowNotification:(NSNotification*)notification
{
   if (!self.popupView.hidden) {
      self.popupView.hidden = YES;
   }
   NSDictionary* userInfo = notification.userInfo;
   CGRect endFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
   CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
   int curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
   CGRect kbFrame = endFrame;
   CGRect editTextFrame = [self.bgView convertRect:self.editingTextLabel.frame toView:self.view];

   //TODO 加上新加的输入框高度
   CGFloat distance = editTextFrame.origin.y + editTextFrame.size.height - (kbFrame.origin.y - 40);
   if (0 < distance) {
      [UIView beginAnimations:nil context:nil];
      [UIView setAnimationCurve:curve];
      [UIView setAnimationDuration:duration];
      CGRect frame = self.bgView.frame;
      frame.origin.y = frame.origin.y - distance - 20;
      self.bgView.frame = frame;
      [UIView commitAnimations];
   }
}

- (void)handleKeyboardDidShowNotification:(NSNotification*)notification
{
   NSDictionary* userInfo = notification.userInfo;
   CGRect endFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
   self.keyboardView.frame = CGRectMake(0, endFrame.origin.y - 80, endFrame.size.width, endFrame.size.height + 80);
   self.keyboardView.hidden = NO;
   [self.keyboardView updateInputStatus:KeyboardInputTypeNormal];
   [self.keyboardView updateSystemKeyboardRect:endFrame];
   [self addTransparentViewBelow:self.popupView];
   [self hideEditView];
   [self.keyboardView updatePosition:NO];
   //去掉心情库button的大小
//   CGRect keyboradFrame = self.keyboardView.frame;
//   CGRect newRect = CGRectMake(keyboradFrame.origin.x, keyboradFrame.origin.y + 20, keyboradFrame.size.width, keyboradFrame.size.height - 20);
}

- (void)handleKeyboardWillHideNotification:(NSNotification*)notification
{
   [self.keyboardView updatePosition:YES];
   if (self.originalY == self.bgView.frame.origin.y) {
      return;
   }
   NSDictionary* userInfo = notification.userInfo;
   CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
   int curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
   [UIView beginAnimations:nil context:nil];
   [UIView setAnimationCurve:curve];
   [UIView setAnimationDuration:duration];
   CGRect frame = self.bgView.frame;
   frame.origin.y = self.originalY;
   self.bgView.frame = frame;
   [UIView commitAnimations];
}

- (void)textLabelTouchBegan:(JSTextLabel*)label
{
   self.editingTextLabel = label;
   @weakify(self)
   if (self.keyboardView == nil) {
      self.keyboardView = [JSKeyboardView keyboardView];
      self.keyboardView.hidden = YES;
      JSKeyboardFontCellModel * cellModel0 = [[JSKeyboardFontCellModel alloc] init];
      cellModel0.fontImage = [UIImage imageNamed:@"Baskerville－Italic"];
      cellModel0.type = JSKeyboardFontCellTypeNormal;
      
      JSKeyboardFontCellModel * cellModel1 = [[JSKeyboardFontCellModel alloc] init];
      cellModel1.fontImage = [UIImage imageNamed:@"DINCond-Medium"];
      cellModel1.type = JSKeyboardFontCellTypeNormal;
      
      JSKeyboardFontCellModel * cellModel2 = [[JSKeyboardFontCellModel alloc] init];
      cellModel2.fontImage = [UIImage imageNamed:@"Snell Roundhand－Regular"];
      cellModel2.type = JSKeyboardFontCellTypeNormal;
      
      JSKeyboardFontCellModel * cellModel3 = [[JSKeyboardFontCellModel alloc] init];
      cellModel3.fontImage = [UIImage imageNamed:@"Tamil MN－Regular"];
      cellModel3.type = JSKeyboardFontCellTypeNormal;
      
      JSKeyboardFontCellModel * cellModel4 = [[JSKeyboardFontCellModel alloc] init];
      cellModel4.fontImage = [UIImage imageNamed:@"SourceHanSans-ExtraLight"];
      cellModel4.type = JSKeyboardFontCellTypeNormal;
      
      JSKeyboardFontCellModel * cellModel5 = [[JSKeyboardFontCellModel alloc] init];
      cellModel5.fontImage = [UIImage imageNamed:@"STHeiti-Light"];
      cellModel5.type = JSKeyboardFontCellTypeNormal;
      
      JSKeyboardViewModel * viewModel = [[JSKeyboardViewModel alloc] init];
      viewModel.inputText = label.text;
      viewModel.fontCellModels = @[cellModel0, cellModel1, cellModel2, cellModel3, cellModel4, cellModel5];
      self.keyboardView.viewModel = viewModel;
      [self.view addSubview:self.keyboardView];
      self.keyboardView.chooseColorBlock = ^ (UIColor * color)
      {
         label.textColor = color;
      };
      self.keyboardView.downloadFontBlock = ^ (NSInteger index)
      {
         // TODO
      };
      self.keyboardView.cancelFontBlock = ^ (NSInteger index)
      {
         // TODO
      };
      self.keyboardView.chooseFontBlock = ^ (NSInteger index)
      {
         switch (index) {
            case 0:
            {
               UIFont * font = [[JSFontManager sharedInstance] baskervilleItalicFontWithSize:label.font.pointSize];
               label.font = font;
            }
               break;
            case 1:
            {
               UIFont * font = [[JSFontManager sharedInstance] dinCondensedFontWithSize:label.font.pointSize];
               label.font = font;
            }
               break;
            case 2:
            {
               UIFont * font = [[JSFontManager sharedInstance] snellRoundhandFontWithSize:label.font.pointSize];
               label.font = font;
            }
               break;
            case 3:
            {
               UIFont * font = [[JSFontManager sharedInstance] tamiilSangamMNFontWithSize:label.font.pointSize];
               label.font = font;
            }
               break;
            case 4:
            {
               UIFont * font = [[JSFontManager sharedInstance] sourceHanSansExtraLightFontWithSize:label.font.pointSize];
               label.font = font;
            }
               break;
            case 5:
            {
               UIFont * font = [[JSFontManager sharedInstance] heitiSCLightFontWithSize:label.font.pointSize];
               label.font = font;
            }
               break;
               
            default:
               break;
         }
      };
      self.keyboardView.xinqingBlock = ^
      {
         @strongify(self)
         [self performSegueWithIdentifier:@"presentXQLib" sender:nil];
      };
      self.keyboardView.textChangeBlock = ^ (id text)
      {
         @strongify(self)
         [self setProperTextLabel:label withString:text];
      };
      self.keyboardView.okBlock = ^{
      };
   }

}

- (void)setProperTextLabel:(JSTextLabel*)label withString:(NSString*)string
{
   if (string.length <= 0) {
      string = @" ";
   }
   NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];
   [attributedString.mutableString setString:string];
   
   UIFont* font = label.font;
   CGRect rect = [attributedString boundingRectWithSize:CGSizeMake(label.frame.size.width - 8, CGFLOAT_MAX)
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                             context:nil];
   NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
   paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
   paragraphStyle.alignment = label.textAlignment;
   if (rect.size.height >= label.frame.size.height && string.length > label.attributedText.length) {
      if (font.pointSize - 1 >= label.minimumFontSize) {
         UIFont* newFont = [font fontWithSize:font.pointSize - 1];
         NSDictionary *attributes = @{NSFontAttributeName : newFont, NSParagraphStyleAttributeName : paragraphStyle};
         [attributedString setAttributes:attributes range:NSMakeRange(0, attributedString.length)];
      }
   } else if (string.length < label.attributedText.length){
      NSDictionary *attributes = @{NSFontAttributeName : [font fontWithSize:font.pointSize + 1], NSParagraphStyleAttributeName : paragraphStyle};
      NSMutableAttributedString* tempStr = [[NSMutableAttributedString alloc] initWithString:attributedString.string attributes:attributes];
      CGRect newRect = [tempStr boundingRectWithSize:CGSizeMake(label.frame.size.width, CGFLOAT_MAX)
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                             context:nil];
      if (font.pointSize < label.defaultFontSize
          && newRect.size.height <= label.frame.size.height) {
         UIFont* newFont = [font fontWithSize:font.pointSize + 1];
//         label.font = newFont;
         NSDictionary *attributes = @{NSFontAttributeName : newFont};
         [attributedString setAttributes:attributes range:NSMakeRange(0, attributedString.length)];
      }
   } else {
      NSDictionary *attributes = @{NSFontAttributeName : font, NSParagraphStyleAttributeName : paragraphStyle};
      [attributedString setAttributes:attributes range:NSMakeRange(0, attributedString.length)];
   }
   label.attributedText = attributedString;
}

- (void)handleXQSelected:(NSNotification*)noti
{
   NSString* xqString = [noti object];
   [self.keyboardView setContentText:xqString];
   [self setProperTextLabel:self.editingTextLabel withString:xqString];
}

- (void)dealloc
{
   [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//- (void)dismissKeyBoardView
//{
//   @weakify(self)
//   [UIView animateWithDuration:0.5
//                    animations:^{
//                       @strongify(self)
//                       self.keyboardView.frame = CGRectOffset(self.keyboardView.frame, 0, self.keyboardView.frame.size.height);
//                    } completion:^(BOOL finished) {
//                       @strongify(self);
//                       [self.keyboardView removeFromSuperview];
//                    }];
//   self.keyboardView= nil;
//}


@end
